#include<avr/io.h>
#include<avr/interrupt.h>
#include "adc.h"
#include "usart.h"

void init_adc(void) {
    ADMUX = (0 << REFS1) | (1 << REFS0); // Reference
    ADCSRA |= (1 << ADEN) | (1 << ADIE) | (1 << ADPS2) | (1 << ADPS1) | (0 << ADPS0); //Prescalar at 64
    init_timer();
}

void init_timer(void){
    TCCR2 |= (1 << WGM21) | (0 << WGM20);
    TIMSK |= (1 << OCIE2);
}

void start_timer(void){
    TCNT2 = 0;
    OCR2 = 25;
    TCCR2 |= (1 << CS22) | (0 << CS21) | (0 << CS20); //Prescalar at 64
}

void stop_timer(void){
    TCCR2 &= ~((1 << CS22) | (1 << CS21) | (1 << CS20));
}

ISR(ADC_vect){
    static uint8_t adco[2] = {0};
    adco[0] = ADCL;
    adco[1] = (ADCH & 0x03);
    usart_send_byte(0x80 | adco[1]);
    usart_send_byte(adco[0]);
}

ISR(TIMER2_COMP_vect){
    ADCSRA |= (1 << ADSC);
}
